<template>
  <div class="app-container table-app-container">
    <div class="fixed-table">
      <ActionBar
        ref="actionBar"
        :locked="locked"
        :categories="categories"
        :belongs="belongs"
        :status="status"
        :status-code="statusCode"
        :for-selection="forSelection"
        :small-type-code="smallTypeCode"
        :type-search-show="typeSearchShow"
        :specifications="specifications"
        :status-search-show="statusSearchShow"
        :org-search-show="orgSearchShow"
        :management-org-code="$attrs['management-org-code']"
      />
      <AssetTable
        :columns="insideColumns"
        :loading="loading"
        :data="insideTableData"
        :total="totalElements"
        :page="currentPage"
        :page-size="pageSize"
        :table-height="tableHeight"
        class="fixed-table-table"
        :show-advanced-search="true"
        @page-change="onPageChange"
        @sort-change="onSortChange"
        @selection-change="onSelectionChange"
        @open-drawer="onOpenDrawer"
        @close-filter-item="onCloseFilterItem"
      >
        <template v-for="column in insideColumns">
          <el-table-column v-if="column.display" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable" :fixed="column.fixed">
            <template slot-scope="scope">
              <column-render :render="column.render" :row="scope.row" :column="column" />
            </template>
          </el-table-column>
        </template>
      </AssetTable>
    </div>
    <ViewDialog
      class="fixed-dialog-height"
      title="资产信息"
      :show.sync="dialogViewVisible"
      width="70%"
      @on-cancel="viewCancel"
    >
      <ViewForm v-if="dialogViewVisible" :id="editId" :categories="categories" :belongs="belongs" :instance="instance" />
    </ViewDialog>
    <FormDialog
      class="fixed-dialog-height"
      title="编辑"
      :show.sync="dialogFormVisible"
      width="90%"
      @on-ok="ok"
      @on-cancel="cancel"
    >
      <EditForm :id="editId" ref="editForm" :categories="categories" :belongs="belongs" />
    </FormDialog>
    <FormDialog
      ref="filterDialog"
      :drawer="true"
      width="40%"
      title="筛选"
      cancel-text="重置"
      confirm-text="筛选"
      :show.sync="drawerFormVisible"
      @on-ok="onSearch"
      @on-cancel="onReset"
    >
      <table-filter
        ref="filterForm"
        :locked="locked"
        :categories="categories"
        :belongs="belongs"
        :status="status"
        :status-code="statusCode"
        :small-type-code="smallTypeCode"
        :type-search-show="typeSearchShow"
        :specifications="specifications"
        :status-search-show="statusSearchShow"
        :org-search-show="orgSearchShow"
        :management-org-code="$attrs['management-org-code']"
        @searchCtx="doSearch"
      />
    </FormDialog>
  </div>
</template>

<script>
// secondary package based on el-pagination
import ViewDialog from '@neu/biz-core/components/ViewDialog'
import FormDialog from '@neu/biz-core/components/FormDialog'
// 表格查询组件独立编写，需要传递asset-table实例的mixin方法filter
import TableFilter from './components/tableFilter'
// 编辑实例组件独立编写，需要传递id属性，判断新建还是更新操作
import ViewForm from './components/viewForm/index'
import EditForm from './components/editForm'
import ActionBar from './components/actionBar'
import AssetTable from '@neu/biz-core/components/AssetTable'

import { page, remove, batchRemove, markLabelPrinted } from '@neu/dcam-ui/api/fixedAsset'
import databind from '@neu/biz-core/mixins/databind'
import { formatDate, isArray } from '@neu/biz-core/utils/utils'
import belongs from '@neu/dcam-ui/mixins/belongs'
import Printer from './Printer'
import { getMyPrinter } from '@neu/dcam-ui/api/printer'
import { ASSET_STATUS as assetStatus } from '@neu/dcam-ui/utils/constants'
import { tree as locationTree } from '@neu/dcam-ui/api/location'

export default {
  name: 'PermissionsPage',
  components: {
    TableFilter,
    FormDialog,
    EditForm,
    ActionBar,
    AssetTable,
    ViewDialog,
    ViewForm
  },
  // 加入混入
  mixins: [databind, belongs],
  props: {
    // 资产状态数组
    statusCode: {
      type: String,
      default: ''
    },
    // 单个资产状态
    status: {
      type: String,
      default: ''
    },
    // 控制状态查询条件控件是否显示
    statusSearchShow: {
      type: Boolean,
      default: true
    },
    // 资产锁定标志
    locked: {
      type: Boolean,
      default: null
    },
    // 资产小分类
    smallTypeCode: {
      type: String,
      default: ''
    },
    // 控制资产类型查询条件控件是否显示
    typeSearchShow: {
      type: Boolean,
      default: true
    },
    // 控制部门查询条件控件是否显示
    orgSearchShow: {
      type: Boolean,
      default: true
    },
    // 规格型号
    specifications: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      r: page,
      d: remove,
      ds: batchRemove,
      insideColumns: [
        { title: '原始编号', width: 100, key: 'originalCode', sortable: 'custom', display: true },
        { title: '资产名称', width: 140, key: 'name', sortable: 'custom', display: true,
          render: (h, params) => { // 查看功能
            if (!this.forSelection) {
              return h('span', [
                h('el-link', {
                  class: 'font-12',
                  attrs: { title: params.row.name },
                  props: { type: 'primary' },
                  on: { click: () => { this.view(params.row) } }},
                params.row.name)
              ])
            } else {
              return h('span', params.row.name)
            }
          }
        },
        { title: '资产编号', width: 140, key: 'code', sortable: 'custom', display: true,
          render: (h, params) => { // 查看功能
            if (!this.forSelection) {
              return h('span', [
                h('el-link', {
                  class: 'font-12',
                  attrs: { title: params.row.code },
                  props: { type: 'primary' },
                  on: { click: () => { this.view(params.row) } }},
                params.row.code)
              ])
            } else {
              return h('span', params.row.code)
            }
          }
        },
        { title: '资产卡片', width: 100, key: 'card', sortable: 'custom', display: false },
        { title: '大分类', width: 100, key: 'bigTypeName', sortable: 'custom', display: true },
        { title: '中分类', width: 100, key: 'middleTypeName', sortable: 'custom', display: true },
        { title: '小分类', width: 100, key: 'smallTypeName', sortable: 'custom', display: true },
        { title: '购置日期', width: 100, key: 'purchaseDate', sortable: 'custom', render: (h, params) => { return h('span', formatDate(params.row.purchaseDate, 'YYYY-MM-DD')) }, display: true },
        { title: '资产状态', width: 100, key: 'status', sortable: 'custom', display: true,
          render: (h, params) => {
            let status = ''
            const one = assetStatus.find(l => l.code === params.row.status)
            if (one) {
              status = one.name
            }
            return h('span', status)
          }
        },
        { title: '供应商', width: 100, key: 'supplierName', sortable: 'custom', display: true },
        { title: '品牌', width: 100, key: 'brand', sortable: 'custom', display: true },
        { title: '规格型号', width: 100, key: 'specifications', sortable: 'custom', display: true },
        { title: '序列号', width: 100, key: 'serialnumber', sortable: 'custom', display: true },
        { title: '机房', width: 100, key: 'computerRoom', sortable: 'custom', display: true },
        { title: '机柜', width: 100, key: 'cabinet', sortable: 'custom', display: true },
        { title: '位置', width: 150, key: 'locationName', sortable: 'custom', display: true,
          render: (h, params) => {
            let locationName = '-'
            if (params.row.location) {
              const trees = this.findParent(params.row.location, this.allLocations)
              if (trees) {
                const names = trees.map(l => l.name)
                locationName = names.join('/')
              }
            }
            return h('span', locationName)
          }
        },
        { title: '维保开始', width: 150, key: 'maintenanceStartTime', render: (h, params) => { return h('span', formatDate(params.row.maintenanceStartTime, 'YYYY-MM-DD')) }, display: true },
        { title: '维保结束', width: 150, key: 'maintenanceEndTime', render: (h, params) => { return h('span', formatDate(params.row.maintenanceEndTime, 'YYYY-MM-DD')) }, display: true },
        { title: '合同', width: 100, key: 'contractNo', sortable: 'custom', display: true },
        { title: '计量单位', width: 100, key: 'measureUnit', sortable: 'custom', display: true },
        { title: '数量', width: 100, key: 'amount', sortable: 'custom', display: true },
        { title: '金额', width: 100, key: 'money', sortable: 'custom', display: true },
        { title: '使用期限', width: 100, key: 'usePeriod', sortable: 'custom', display: true },
        { title: '使用部门', width: 150, key: 'managementOrgName', sortable: 'custom', display: true },
        { title: '使用人', width: 100, key: 'managementUserName', sortable: 'custom', display: true },
        { title: '标签打印', width: 100, key: 'labelPrinted', sortable: 'custom', display: true,
          render: (h, params) => {
            return h('span', params.row.labelPrinted === true ? '已打印' : '')
          }
        },
        { title: '用途', key: 'purpose', display: true },
        { title: '备注', key: 'note', display: true }
      ],
      dialogFormVisible: false,
      dialogViewVisible: false,
      dialogStatus: 'create',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      searchObj: {
        s_belongs: ''
      },
      editId: -1,
      drawerFormVisible: false,
      instance: {},
      allLocations: []
    }
  },
  created() {
    this.$store.dispatch('dcam/setAssetSearchObj', {})
    if (this.statusCode) {
      this.searchObj['s_statusCode'] = this.statusCode
    }
    if (this.status) {
      this.searchObj['s_status'] = this.status
    }
    if (this.locked != null) {
      this.searchObj['s_locked'] = this.locked
    }
    if (this.smallTypeCode != null) {
      this.searchObj['s_smallTypeCode'] = this.smallTypeCode
    }
    if (this.specifications != null) {
      this.searchObj['s_specifications'] = this.specifications
    }

    if (this.$attrs['management-org-code']) {
      this.searchObj['s_managementOrgCode'] = this.$attrs['management-org-code']
    } else { // 操作员所属的部门及子部门
      var orgArr = this.$store.getters.orgs
      var operatorOrgCode = ''
      for (var i in orgArr) {
        operatorOrgCode += orgArr[i] + '-'
      }
      this.searchObj['s_operatorOrgCode'] = operatorOrgCode
    }
    if (this.$attrs['location-arr']) {
      this.searchObj['s_locationArr'] = this.$attrs['location-arr'].join(',')
    }
    if (this.$attrs['type-arr']) {
      this.searchObj['s_typeCodesArr'] = this.$attrs['type-arr'].join(',')
    }
    this.searchObj.s_belongs = this.belongs
    this.searchObj.s_categories = this.categories
    this.filter(this.searchObj)

    let hiddenColumns = []
    if (this.categories === '3') {
      hiddenColumns = ['bigTypeName', 'middleTypeName', 'originalCode', 'supplierName', 'code', 'card', 'serialnumber', 'computerRoom', 'cabinet', 'location', 'maintenanceStartTime', 'maintenanceEndTime', 'contractNo', 'usePeriod', 'managementOrgName', 'managementUserName', 'purchaseDate', 'status', 'brand', 'specifications', 'locationName', 'money', 'labelPrinted']
    } else {
      if (this.belongs === 'sl') {
        hiddenColumns = ['computerRoom', 'cabinet', 'amount']
      } else {
        hiddenColumns = ['card', 'amount']
      }
    }
    this.insideColumns = this.insideColumns.filter(e => !hiddenColumns.includes(e.key))

    const originalCodeColumn = this.insideColumns.find(it => it.key === 'originalCode')
    if (originalCodeColumn) {
      if (this.belongs === 'kj') {
        originalCodeColumn.title = '原始编码'
      } else if (this.belongs === 'sl') {
        originalCodeColumn.title = '资产卡片'
      }
    }

    // 位置信息
    locationTree(this.belongs).then(response => {
      var availableLocations = response.data
      this.allLocations = this.flattenTreeDataClosure(availableLocations)
    })
  },
  methods: {
    onSearch() { // 筛选-筛选
      this.$refs.filterForm.search()
      this.drawerFormVisible = false
    },
    onReset() { // 筛选-重置
      this.$refs.filterForm.reset()
      this.drawerFormVisible = false
    },
    onOpenDrawer() { // 筛选-打开抽屉
      this.drawerFormVisible = true
      this.$refs.actionBar.clearForm()
    },
    onCloseFilterItem(item) {
      this.$refs.filterForm.onFilterItemClose(item)
    },
    view(row) {
      // 打开对话框
      this.editId = row.id
      this.instance = row
      this.dialogViewVisible = true
    },
    edit(selections) {
      if (isArray(selections)) {
        if (selections.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择操作数据！'
          })
          return
        }
        if (selections.length > 1) {
          this.$message({
            type: 'warning',
            message: '只能选择一条数据！'
          })
          return
        }

        if (selections[0].locked === true) {
          this.$message({
            type: 'warning',
            message: '此资产正在走流程，不能编辑！'
          })
          return
        }

        // 更新当前被编辑实体的ID，自动传递至编辑表单
        this.editId = selections[0].id
        // 打开对话框
        this.dialogFormVisible = true
      }
    },
    ok() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        // 调用asset-table实例的mixin方法refresh()，更新表格
        this.refresh()
        // 关闭对话框
        this.dialogFormVisible = false
      })
    },
    cancel() {
      this.editId = -1
      this.$refs.editForm.reset()
      this.dialogFormVisible = false
    },
    viewCancel() {
      this.editId = -1
      // 关闭对话框
      this.dialogViewVisible = false
    },
    print(selections) {
      const that = this
      getMyPrinter().then(config => {
        if (config.data && config.data.ip) {
          Printer.connect(config.data, ok => {
            Printer.printLabel(selections)
            markLabelPrinted(selections.map(it => it.id))
          }, error => {
            that.$message({
              showClose: true,
              message: error,
              type: 'warning'
            })
          })
        } else {
          that.$message({
            showClose: true,
            message: '未设置打印机，请先设置打印机',
            type: 'warning'
          })
        }
      })
    },
    // 扁平化树形结构
    flattenTreeDataClosure(data) {
      const treeData = data
      const flattenData = []
      function flattenTree(data, parentKey) {
        data.forEach(ele => {
          const { title, code, children } = ele
          flattenData.push({ title, code, parentKey })
          if (children) {
            flattenTree(children, code)
          }
        })
      }
      flattenTree(treeData, null)
      return flattenData
    },
    findParent(item, flattenTree) {
      const parentArr = [] // 存储所有的父级元素
      function find(item, flattenTree) {
        flattenTree.forEach(ele => {
          if (ele.code === item) {
            parentArr.unshift({ code: ele.code, name: ele.title })
            find(ele.parentKey, flattenTree)
          }
        })
      }
      find(item, flattenTree)
      return parentArr
    },
    doSearch(searchCtx) {
      this.filter(searchCtx)
    }
  }
}
</script>
